/**
 * Created by chencheng on 17-8-30.
 */
import { Toast, Dialog, type DialogProps } from "@nutui/nutui-react-taro";
// import Taro from "@tarojs/taro";

class Prompt {

  // 注意: id值要和src/layout/Scaffold/index.tsx文件中的一致
  toastId = "x_toast_id";
  dialogId = "x_dialog_id";

  constructor() {

  }

  /**
   * 消息
   * @param {String} msg
   * @param {Number} duration
   */
  info(msg: string, duration = 2000) {
    // Taro.showToast({title: msg, icon: "none", duration})
    this.hide();
    Toast.show(this.toastId, {msg, duration: duration / 1000})
  }

  /**
   * 提示成功
   */
  success(msg: string, duration = 2000) {
    // Taro.showToast({title: msg, icon: "success", duration})
    this.hide();
    Toast.show(this.toastId, {msg, type: "success", duration: duration / 1000})
  }

  /**
   * 提示错误
   */
  error(msg: string, duration = 2000) {
    if (Array.isArray(msg)) {
      let newMsg = "";
      msg.forEach(item => newMsg += `${item.message}\n`);
      msg = newMsg;
    }

    // Taro.showToast({title: msg, icon: "error", duration})
    this.hide();
    Toast.show(this.toastId, {msg, type: "fail", duration: duration / 1000})
  }

  /**
   * 提示警告
   */
  warn(msg: string, duration = 2000) {
    // Taro.showToast({title: msg, icon: "error", duration})
    this.hide();
    Toast.show(this.toastId, {msg, type: "warn", duration: duration / 1000})
  }

  /**
   * 加载动画
   */
  loading(params?:{msg?: string, duration?: number}) {
    const {msg = "加载中", duration = 0} = params || {};
    // Taro.showLoading({title: msg})
    this.hide();
    Toast.show(this.toastId, {msg, type: "loading", duration: duration / 1000})
  }

  /**
   * 关闭提示
   */
  hide(){
    // Taro.hideToast()
    Toast.hide(this.toastId);
  }

  /**
   * 开启对话框
   */
  openDialog = (options: DialogProps) => {
    this.closeDialog()
    Dialog.open(this.dialogId, options)
  }

  /**
   * 关闭对话框
   */
  closeDialog = () => {
    Dialog.close(this.dialogId)
  }
}

export default new Prompt();
